package com.jin.spirng_boot_learn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServiceSocketChannelExam {


    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 打开一个socket
        serverSocketChannel.socket().bind(new InetSocketAddress(9999)); // 绑定端口
        serverSocketChannel.configureBlocking(false);
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            //
            if (socketChannel != null) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                String content = "";
                try {
                    int readBytes = socketChannel.read(byteBuffer);
                    if (readBytes > 0) {
                        byteBuffer.flip(); //为write()准备
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(bytes);
                        content += new String(bytes);
                        System.out.println(content);
                        //回应客户端
                        doWrite(socketChannel);
                    }
                } catch (Exception e) {
                }
            }
                System.out.println("完成一次accept");
        }
    }
    private  static void doWrite(SocketChannel sc) throws IOException {
        byte[] req ="服务器已接受".getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(req.length);
        byteBuffer.put(req);
        byteBuffer.flip();
        sc.write(byteBuffer);
        if(!byteBuffer.hasRemaining()){
            System.out.println("Send 2 Service successed");
        }
    }
}
